<template>
	<el-dialog class="abow-dialog" top="9vh" :visible.sync="visible" :title="!userId ? '新增' : '修改'" :close-on-click-modal="false"
		:close-on-press-escape="false" width="700px">
		<el-form class="form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px" size="medium"
			labelSuffix="：">
			<el-form-item prop="username" label="用户名">
				<el-input clearable v-model="dataForm.username" placeholder="用户名" />
			</el-form-item>
			<el-form-item prop="real_name" label="姓名">
				<el-input clearable v-model="dataForm.real_name" placeholder="姓名" />
			</el-form-item>
			<el-form-item prop="password" label="密码">
				<el-input clearable :readonly="userId?readonlyInput:new_readonlyInput" @focus="cancelReadOnly()" type="password" autocomplete="off" v-model="dataForm.password" placeholder="密码" />
			</el-form-item>
			<el-form-item prop="password_repeat" label="重复密码">
				<el-input clearable :readonly="userId?readonlyInput:new_readonlyInput" @focus="cancelReadOnly()" type="password" v-model="dataForm.password_repeat" autocomplete="off" placeholder="重复密码" />
			</el-form-item>
			<el-form-item prop="status" label="状态">
				<el-select clearable v-model="dataForm.status" placeholder="请选择">
					<el-option v-for="(item,index) in status" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item prop="phone" label="手机号">
				<el-input clearable v-model="dataForm.phone" placeholder="手机号" />
			</el-form-item>
			<el-form-item prop="email" label="邮箱">
				<el-input clearable v-model="dataForm.email" placeholder="邮箱" />
			</el-form-item>
			<el-form-item prop="roles_ids" label="用户绑定角色">
				<el-select clearable v-model="dataForm.roles_ids" multiple placeholder="请选择" @focus="rolesFocusFn">
					<el-option v-for="(item,index) in roleName" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item prop="company_id" label="公司">
				<el-select clearable  v-model="dataForm.company_id" placeholder="请选择" @focus="companyFocusFn">
					<el-option v-for="(item,index) in companyName" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item prop="sort" label="排序">
				<el-input v-model="dataForm.sort" type="number" placeholder="排序" />
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('views.public.confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
	import {mapState} from 'vuex'
	import {
		debounce
	} from 'lodash'
	import {
		isEmail,
		isMobile
	} from '@/libs/validate'
	import schema from 'async-validator'
	export default {
		data() {
			return {
				userId:null,
				readonlyInput: true,
				new_readonlyInput: true,
				status:[{
					value:0,
					label:'未启用',
				},{
					value:1,
					label:'正常',
				},
				{
					value:2,
					label:'禁用',
				},
				{
					value:3,
					label:'重置密码',
				}],
				roleName: [],
				companyName: [],
				visible: false,
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				roleList: [],
				roleIdListDefault: [],
				dataForm: {
					username: '', //用户名
					real_name: '', //姓名
					password: '', //密码
					password_repeat: '', //重复密码
					status: '', //状态
					phone: '', //手机号
					email: '', //邮箱
					roles_ids: [], //用户绑定角色
					company_id: '', //公司
					sort: 0 //排序
				}
			}
		},
		created() {
		},
		computed: {
			...mapState('d2admin/user', [
				'info'
			]),
			dataRule() {
				var validateName = (rule, value, callback) => {
					if (!/\S/.test(value)) {
						return callback(new Error(this.$t('public.rules.required', {
							name: '用户名不能为空！'
						})))
					}
					callback()
				}
				//密码
				var validatePassword = (rule, value, callback) => {
					//新建用户要密码
					if(!this.userId){
						if (!/\S/.test(value)) {
							return callback(new Error(this.$t('public.rules.required', {
								name: this.$t('views.public.user.password')
							})))
						}
					}else{
						if(typeof value == 'string' || typeof value == 'number'){
							if (value.length>0 && value.length<6) {
								return callback(new Error(this.$t('public.rules.required', {
									name: this.$t('views.public.user.password')
								})))
							}
						}
					}
					callback()
				}
				//重复密码
				var validateComfirmPassword = (rule, value, callback) => {
					//新建用户要重复密码
					console.log(value);
					if(!this.userId){
						if (!/\S/.test(value)) {
							return callback(new Error(this.$t('public.rules.required', {
								name: this.$t('views.public.user.comfirmPassword')
							})))
						}
						if (this.dataForm.password !== value) {
							return callback(new Error(this.$t('views.public.user.validate.comfirmPassword')))
						}
					}else{
						if(typeof value == 'string' || typeof value == 'number'){
							if (value.length>0 && value.length<6) {
								return callback(new Error(this.$t('public.rules.required', {
									name: this.$t('views.public.user.comfirmPassword')
								})))
							}
						}
						if(typeof this.dataForm.password == 'string' || typeof this.dataForm.password == 'number'){
							if (this.dataForm.password.length>0&&this.dataForm.password !== value) {
								return callback(new Error(this.$t('views.public.user.validate.comfirmPassword')))
							}
						}
					}
					callback()
				}
				var validateMobileAsync = (rule, value, callback) => {
					if (/\S/.test(value)&&!isMobile(value)) {
						return callback(new Error(this.$t('public.rules.format', {
							name: this.$t('views.public.user.mobile')
						})))
					}
					callback()
				}
				var validateEmail = (rule, value, callback) => {
					if (/\S/.test(value)&&!isEmail(value)) {
						return callback(new Error(this.$t('public.rules.format', {
							name: this.$t('views.public.user.email')
						})))
					}
					callback()
				}
				return {
					username: [{
							required: true,
							message: '用户名不能为空!',
							trigger: ['blur','change']
						}
					],
					real_name: [{
							required: true,
							message: '姓名不能为空!',
							trigger: ['blur','change']
						}
					],
					password: [{
						required: this.userId?false:true,
						validator: validatePassword,
						trigger: ['blur','change']
					}],
					password_repeat: [{
						required: this.userId?false:true,
						validator: validateComfirmPassword,
						trigger: ['blur','change']
					}],
					status: [{
						required: true,
						message: '状态不能为空!',
						trigger: ['blur','change']
					}],
					phone: [{
						required: false,
						validator: validateMobileAsync,
						trigger: ['blur','change']
					}],
					email: [{
						required: false,
						validator: validateEmail,
						trigger: ['blur','change']
					}],
					roles_ids: [{
							required: true,
							message: '用户绑定角色不能为空！',
							trigger: ['blur','change']
						}
					],
					sort: [{
						required: true,
						message: '排序不能为空！',
						trigger: ['blur','change']
					}]
				}
			}
		},
		methods: {
			cancelReadOnly() {
				if(this.userId){
					this.readonlyInput= false;
				}else{
					this.new_readonlyInput= false;
				}
			},
			//角色列表
			async rolesFocusFn(){
				const roleRes = await this.$axios.get('/api/common/auth-role');
				this.roleName = roleRes;
			},
			//公司列表
			async companyFocusFn(init=true){
				const companyRes = await this.$axios.get('/api/common/company');
				console.log(companyRes);
				if(Array.isArray(companyRes)){
					if(companyRes.length){
						if(init&&!this.userId){
							this.dataForm.company_id = companyRes[0].value;
						}
						this.companyName = companyRes;
						return
					}
				}
				this.dataForm.company_id = "";
				this.companyName = [];
			},
			init() {
				this.visible = true;
				this.readonlyInput= true;//密码框只读，防止浏览器自动填充
				this.new_readonlyInput= true;//密码框只读，防止浏览器自动填充
				this.companyFocusFn();//拿到公司默认值
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields();
				})
			},
			update(row) {
				this.visible = true;
				this.readonlyInput= true;//密码框只读，防止浏览器自动填充
				this.new_readonlyInput= true;//密码框只读，防止浏览器自动填充
				this.rolesFocusFn();
				this.companyFocusFn(false);//拿到公司选中值
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields();
					if(Array.isArray(row.roles_ids)){
						for (var i = 0; i < row.roles_ids.length; i++) {
							if(typeof row.roles_ids[i] == 'string'){
								row.roles_ids[i] = parseInt(row.roles_ids[i]);
							}
						}
					}
					this.dataForm = Object.assign({}, row);
				})
			},

			// 所属部门树, 选中
			deptListTreeCurrentChangeHandle(data, node) {
				this.dataForm.deptId = data.deptId
				this.dataForm.deptName = data.name
				this.deptListVisible = false
			},
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				console.log('表单提交');
				this.$refs.dataForm.validate((valid) => {
					console.log(valid + '--+++++-----------')
					if (!valid) {
						return false
					}
					console.log(this.dataForm);
					this.$axios.post(this.userId?`/api/authority/user/update/${this.userId}`:'/api/authority/user/create', this.dataForm).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 500,
							onClose: () => {
								this.visible = false
								this.$emit('refreshDataList',this.userId?false:true)
							}
						})
						if(this.userId){
							if(this.userId == this.info.user.id){
								if(this.info.user.real_name!=this.dataForm.real_name){
									// console.log('修改自己的，更新昵称');
									this.updateInfo(this.dataForm.real_name);
								}
							}
						}
					}).catch(() => {})
				})
			}, 1000, {
				leading: true,
				trailing: false
			}),
			async updateInfo(new_real_name){
				this.info.user.real_name = new_real_name;
				await this.$store.dispatch('d2admin/db/set', {
				  dbName: 'sys',
				  path: 'user.info',
				  value: this.info,
				  user: true
				}, { root: true })
			}
		}
	}
</script>

<style lang="scss" scoped>
	.form{
		width: 600px;
	}
	.mod-sys__user {
		.dept-list {

			.el-input__inner,
			.el-input__suffix {
				cursor: pointer;
			}
		}

		.role-list {
			.el-select {
				width: 100%;
			}
		}
	}
</style>